import crypto from 'crypto'

export function getInt (obj, key) {
  let n = parseInt(obj[key], 10)
  if (isNaN(n)) n = 0
  return n
}

export function generateDid () {
  return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
    let r = Math.random() * 16 | 0
    let v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

export function getUnixTimestamp () {
  return Math.floor(Date.now() / 1000)
}

export function md5 (text) {
  let md5 = crypto.createHash('md5')
  return md5.update(text).digest('hex')
}

export function hex2bin (e) {
  if (e && e.length % 8 === 0) {
    let arr = []
    for (let i = 0; i < e.length; i += 2) {
      arr.push(e.substr(i, 2))
    }
    let arr2 = []
    for (let i = 0; i < arr.length; i += 4) {
      arr2.push(parseInt(arr.slice(i, i + 4).reverse().join(''), 16))
    }
    return arr2
  }
  return null
}

const fonts = '0123456789abcdef'.split('')
function _hex (e) {
  let t = ''
  for (let n = 0; n < 4; n++) {
    t += fonts[e >> 8 * n + 4 & 15] + fonts[e >> 8 * n & 15]
  }
  return t
}

export function hex (binArr) {
  for (let t = 0; t < binArr.length; t++) {
    binArr[t] = _hex(binArr[t])
  }
  return binArr.join('')
}

export function binEncrypt (binArr) {
  let k = [0x174d4dc8, 0xfb8b26a6, 0x7b5a767d, 0x3b251e1f]
  let rs = 32
  for (let I = 0; I < binArr.length; I += 2) {
    let i
    let v0 = binArr[I]
    let v1 = binArr[I + 1]
    let delta = 0x9E3779B9
    let sum = delta * rs
    v0 -= 0x6b893ed6
    v0 -= 0x3803851c
    v1 ^= 0x1a5690ef
    v1 ^= 0x7a29d82a
    for (i = 0; i < rs; i++) {
      v1 -= (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum + k[(sum >>> 11) & 3])
      sum -= delta
      v0 -= (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum + k[sum & 3])
    }
    v0 ^= 0x93366fd2
    v0 ^= 0xed246977
    v1 -= 0xe508412c
    v1 -= 0x93366fd2
    binArr[I] = v0
    binArr[I + 1] = v1
  }
}
